
function getRootDomain() {
  var rooDomain = ''
  var fullDomain = document.domain
  // 判断是否包含字母，如包含则认为是域名，否则认为是ip
  var isDomain = false
  if (isNaN(fullDomain[fullDomain.length - 1])) {
    isDomain = true
  }
  if (isDomain === true) {
    var fullDomainList = fullDomain.split('.')
    if (fullDomainList.length === 3) {
      rooDomain = fullDomainList.slice(1, 3).join('.')
    } else if (fullDomainList.length > 3) {
      rooDomain = fullDomainList.slice(fullDomainList.length - 3, fullDomainList.length).join('.')
    }
  } else {
    rooDomain = fullDomain
  }
  return rooDomain
}

export function clearAllCookie(times, pattern) {
  var keys = document.cookie.match(/[^ =;]+(?=\=)/g)
  if (keys) {
    for (var i = keys.length; i--;) {
      document.cookie = keys[i] + '=0;path=/;domain=' + getRootDomain() + ';expires=' + new Date(0).toUTCString()
    }
  }
}

export function getCookie(key) {
  var arrCookie = document.cookie.split('; ')
  var value = ''
  for (var i = 0; i < arrCookie.length; i++) {
    var arr = arrCookie[i].split('=')
    if (key === arr[0]) {
      value = arr[1]
      break
    }
  }
  return value
}

export function setCookie(key, value) {
  var exp = new Date()
  var Days = 1
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
  document.cookie = key + '=' + value + ';path=/;domain=' + getRootDomain() + ';expires=' + exp.toGMTString()
}
